package com.drore.logapp.http.interceptor;

import android.util.Log;

import com.drore.app.LogRecordUtil;
import com.drore.www.logbeansecret.bean.NetConnectBean;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/12/11 11:15
 */

public class HttpInterceptor implements Interceptor {
    private static String TAG = "HttpInterceptor";

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Log.e(TAG, "HttpInterceptor coming... ");
        Request request = chain.request();
        String paramsStr = "";
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset();
            }
            paramsStr = buffer.readString(charset);
        }
        Response response = chain.proceed(request);
        if (response != null) {
            String method = response.request().method();
            String url = response.request().url() + "";
            int code = response.code();
            long sentRequestAtMillis = response.sentRequestAtMillis();
            long receivedResponseAtMillis = response.receivedResponseAtMillis();
            long requestDuration = receivedResponseAtMillis - sentRequestAtMillis;
            boolean success = response.isSuccessful();
            String protocol = response.protocol().toString();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("请求方式：" + method).append("\n");
            stringBuilder.append("请求链接：" + url).append("\n");
            stringBuilder.append("请求参数：" + paramsStr).append("\n");
            stringBuilder.append("请求状态码：" + code).append("\n");
            stringBuilder.append("请求开始时间：" + sentRequestAtMillis + "毫秒").append("\n");
            stringBuilder.append("请求结束时间：" + receivedResponseAtMillis + "毫秒").append("\n");
            stringBuilder.append("请求花费时间：" + requestDuration + "毫秒").append("\n");
            stringBuilder.append("请求是否成功：" + success).append("\n");
            stringBuilder.append("请求协议：" + protocol).append("\n");
            //存储请求信息
            LogRecordUtil.setNetDetail(new NetConnectBean(method, url, paramsStr, code, success, sentRequestAtMillis,
                    receivedResponseAtMillis, requestDuration, protocol, ""),true);
            Log.e(TAG, "" + stringBuilder);
        }
        return response;
    }
}
